package com.lb.trac.controller;

import java.lang.reflect.Array;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.lb.trac.pojo.Utenti;
import com.lb.trac.service.SearchService;
import com.lb.trac.util.AbstractBrowser;
import com.lb.trac.util.Browser;
import com.lb.trac.util.Page;
import com.lb.trac.web.json.transformer.JSONTransformer;

public class SearchController extends AbstractController {

	private SearchService searchService;
	private JSONTransformer jsonTransformer;
	private Class  result;
	private Browser browser ;
	
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String limit = request.getParameter("limit");
		String start = request.getParameter("start");
		String page = request.getParameter("page");
		Object[] array = (Object[]) Array.newInstance(result, 0);
		int count = (Integer) getSearchService().count(result);
		Object[] u = getSearchService().find(array,Integer.parseInt( start),Integer.parseInt(limit), result);
		JSONObject json = getJsonTransformer().javaObjectToJsonObject(u);
		json.put("total", count);
		System.out.println(json.toString());
		response.getWriter().write(json.toString());
		return null;
	}
	public SearchService getSearchService() {
		return searchService;
	}
	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}
	public JSONTransformer getJsonTransformer() {
		return jsonTransformer;
	}
	public void setJsonTransformer(JSONTransformer jsonTransformer) {
		this.jsonTransformer = jsonTransformer;
	}
	public Class getResult() {
		return result;
	}
	public void setResult(Class result) {
		this.result = result;
	}
	@Override
	protected void initApplicationContext(ApplicationContext context) {
		if(getResult()==null || getJsonTransformer()==null){
			throw new IllegalArgumentException("Specificare le properties result e jsonTransformer");
		}
	}
	public Browser getBrowser() {
		return browser;
	}
	public void setBrowser(Browser browser) {
		this.browser = browser;
	}

}
